package com.example.java_gobang2.job;

import com.example.java_gobang2.mapper.UserMapper;
import com.example.java_gobang2.model.User;
import com.example.java_gobang2.model.UserRank;
import com.example.java_gobang2.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class Task {
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;
    @Scheduled(cron = "0 0 * * * *")
    public void execute() {
        List<UserRank> userRanks = new ArrayList<>();
        List<User> userList = userMapper.selectUserRank();
        int i = 1;
        for (User user : userList) {
            UserRank userRank = new UserRank();
            userRank.setUsername(user.getUsername());
            userRank.setScore(user.getScore());
            userRank.setRank(i++);
            userRanks.add(userRank);
        }
        log.info("排行榜更新完成");
        redisService.deleteKey("userRank");
        redisService.rightPushAll("userRank",userRanks);
    }
}
